/* eslint-disable no-unused-expressions */
import { updateAdminPassword } from '@/pages/user/Admin/service';
import { SUCCESS_CODE } from '@/utils/request';
import { PlusOutlined } from '@ant-design/icons';
import ProForm from '@ant-design/pro-form';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Divider, Drawer, Form, Input, message, Modal, Tag } from 'antd';
import type { SorterResult } from 'antd/es/table/interface';
import React, { useRef, useState } from 'react';
import AddFrom from './components/AddForm';
import TenantDetail from './components/TenantDetail';
import type { TenantAddItem, TenantTableListItem } from './data.d';
import { addTenant, queryTenantDetail, queryTenantList, removeTenant } from './service';

const TenantTableList: React.FC = () => {
    const [sorter, setSorter] = useState<string>('');
    const [addModalVisible, handleAddModalVisible] = useState<boolean>(false);
    const [detailVisible, setDetailVisible] = useState<boolean>(false);
    const [passwordVisible, setPasswordVisible] = useState<boolean>(false);
    const [selected, setSelected] = useState<TenantTableListItem | undefined>(undefined);

    const actionRef = useRef<ActionType>();

    async function handleAdd(fields: TenantAddItem) {
        const hide = message.loading('正在添加');

        const res = await addTenant(fields);
        hide();
        if (res.code === SUCCESS_CODE) {
            message.success(res.message || '添加成功');
            actionRef.current?.reload();
        } else {
            message.error(res.message || '添加失败请重试！');
        }
        handleAddModalVisible(false);
        return true;
    }

    // 删除
    const handleRemove = async (fields: { id: string }) => {
        const hide = message.loading('正在删除');
        try {
            await removeTenant(fields);
            hide();
            message.success('删除成功');
            actionRef.current?.reload();
            return true;
        } catch (error) {
            hide();
            message.error('删除失败请重试！');
            return false;
        }
    };

    // const handleReset = async (fields: { id: string }) => {
    //   const hide = message.loading('正在重置');
    //   try {
    //     await resetAdmin(fields);
    //     hide();
    //     message.success('重置成功');
    //     return true;
    //   } catch (error) {
    //     hide();
    //     message.error('重置失败请重试！');
    //     return false;
    //   }
    // };

    const columns: ProColumns<TenantTableListItem>[] = [
        {
            title: '客户编号',
            dataIndex: 'id',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: '客户名称',
            dataIndex: 'name',
            ellipsis: true,
        },
        {
            title: '管理员名称',
            dataIndex: 'managerName',
            ellipsis: true,
        },
        {
            title: '管理员账号',
            dataIndex: 'managerAccount',
            ellipsis: true,
        },
        {
            title: '更新时间',
            dataIndex: 'update_time',
            ellipsis: true,

            search: false,
            render: (_, record) => <Tag>{record.update_time}</Tag>,
        },
        {
            title: '操作',
            search: false,
            ellipsis: true,
            render: (_, record) => {
                const onClickDetail = () => {
                    setDetailVisible(true);
                    setSelected(record);
                };

                const onClickRemove = () => {
                    const { id, name } = record;
                    Modal.confirm({
                        title: `删除客户 ${id}`,
                        content: (
                            <>
                                <Divider />
                                <p>确认要删除客户</p>
                                <span>{name}</span>?
                            </>
                        ),
                        okText: '确定',
                        cancelText: '取消',
                        onOk: async () => {
                            await handleRemove({ id });
                        },
                        centered: true,
                        width: '30vw',
                        style: { height: '18vw' },
                    });
                };

                // const onResetPassword = () => {
                //   const { name: tenant_name, manager_admin } = record;

                //   const title = `重置${tenant_name}企业管理员密码?`;

                //   Modal.confirm({
                //     title: title,
                //     content: (
                //       <>
                //         <Divider />
                //         <p>确定要重置密码？</p>
                //         <p style={{ fontWeight: 'bolder' }}>企业客户: {tenant_name} </p>
                //         <p style={{ fontWeight: 'bolder' }}>企业管理员: {manager_admin?.name}</p>
                //       </>
                //     ),
                //     okText: '确定',
                //     cancelText: '取消',
                //     onOk: async () => {
                //       if (manager_admin && manager_admin.admin_id) {
                //         await handleReset({ id: manager_admin?.admin_id });
                //       } else {
                //         message.error('manager_admin.admin_id is null please check it');
                //       }
                //     },
                //   });
                // };

                return (
                    <div>
                        <a onClick={onClickDetail}>详情</a>
                        <Divider type="vertical" />
                        <a
                            onClick={() => {
                                setPasswordVisible(true);
                                setSelected(record);
                            }}
                        >
                            修改密码
                        </a>
                        <Divider type="vertical" />
                        <a onClick={onClickRemove}>删除</a>
                    </div>
                );
            },
        },
    ];
    return (
        <PageHeaderWrapper title="客户管理">
            <ProTable<TenantTableListItem>
                headerTitle={'客户管理'}
                actionRef={actionRef}
                rowKey="id"
                scroll={{ x: true }}
                pagination={{
                    defaultPageSize: 10,
                    size: 'default',
                    showQuickJumper: true,
                    showSizeChanger: true,
                }}
                search={{
                    labelWidth: 'auto',
                    span: { xs: 24, sm: 12, md: 8, lg: 8, xl: 8, xxl: 6 },
                }}
                onChange={(_, _filter, _sorter) => {
                    const sorterResult = _sorter as SorterResult<TenantTableListItem>;
                    if (sorterResult.field) {
                        setSorter(`${sorterResult.field}_${sorterResult.order}`);
                    }
                }}
                params={{
                    sorter,
                }}
                toolBarRender={() => [
                    <Button type="primary" key={''} onClick={() => handleAddModalVisible(true)}>
                        <PlusOutlined /> 添加
                    </Button>,
                ]}
                tableAlertRender={() => false}
                request={(params = {}) => {
                    return queryTenantList(params);
                }}
                columns={columns}
                rowSelection={false}
            />
            {addModalVisible && (
                <AddFrom
                    modalVisible={addModalVisible}
                    onSubmit={(value) => handleAdd(value)}
                    onCancel={() => handleAddModalVisible(false)}
                />
            )}
            <Drawer
                visible={!!selected && detailVisible}
                onClose={() => setDetailVisible(false)}
                width="320px"
            >
                {!!selected && detailVisible && (
                    <TenantDetail
                        tenant={selected}
                        reloadFunc={() => actionRef.current?.reload()}
                        request={(id: any) => queryTenantDetail({ id })}
                    />
                )}
            </Drawer>
            <Modal
                footer={null}
                visible={passwordVisible}
                style={{ marginBottom: 100 }}
                centered
                title="修改密码"
                destroyOnClose
                onCancel={() => {
                    setPasswordVisible(false);
                }}
            >
                <ProForm
                    layout="horizontal"
                    onFinish={async (value) => {
                        const values = {
                            password: value.password,
                            admin_id: selected?.manager_admin?.admin_id,
                        };
                        const hide = message.loading('正在修改');
                        const res = await updateAdminPassword(values);
                        hide();
                        if (res.code === 0) {
                            message.success(`${res.message}`);
                            setPasswordVisible(false);
                            actionRef.current?.reload();
                            return true;
                        } else {
                            message.error(`${res.message}`);
                            return false;
                        }
                    }}
                >
                    <Form.Item
                        name="password"
                        label="新密码"
                        rules={[{ required: true, message: '新密码不能为空' }]}
                    >
                        <Input type="password" />
                    </Form.Item>
                </ProForm>
            </Modal>
        </PageHeaderWrapper>
    );
};

export default TenantTableList;
